<template>
	<view class="container">
		<view style="margin: 0 auto;">
			<!-- 头部logo -->
			<h1 style="text-align: center;font-size: x-large;padding: 100rpx ;">
				手帐One
			</h1>
			<!-- 主体表单 -->
			<uni-forms :value="formData" ref="form" :rules="rules" >
				<uni-forms-item label="手机号" name="username">
					<uni-easyinput type="text" v-model="formData.username" focus placeholder="请输入账号" />
				</uni-forms-item>
				<uni-forms-item label="密码" name="password">
					<uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" />
				</uni-forms-item>
				<button style="margin-top:30rpx ;" type="primary" @click="submitForm">登 录</button>
				<button style="margin-top:30rpx ;" type="" @click="registForm" >注 册</button>
				<!-- 该APPID没有获取手机号的权限，详见https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
				<button class='bottom' type='primary' open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">获取手机号</button> -->
				<!-- <button style="margin-top:25rpx ;" type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="bindGetUserInfo">
				  获取用户信息
				</button> -->
				<!-- <image :src="avatarUrl"></image>
				
				{{nickName}}{{avatarUrl}}
				<view>纬度{{latitude}}经度{{longitude}}</view> -->
				
			</uni-forms>
		</view>
	</view>
</template>

<script>
	import { login,regist,getOpenid,decode } from '@/api/public.js'
	export default {
		
		data() {
			return {
				code:"",
				sessionKey: '',
				encryptedData:"",
				iv:"",
				openId: '', //用户在当前小程序的唯一标识
				nickName: null,
				avatarUrl: null,
				isCanUse: uni.getStorageSync('isCanUse'), //默认为true  记录当前用户是否是第一次授权使用的
				latitude:0,
				longitude:0,
				
				formData:{
					username:'18900001234',
					password:'123456'
				},
				rules: {
					// 对name字段进行必填验证
					username: {
						rules: [{
								required: true,
								errorMessage: '请输入手机号',
							},
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '手机号长度为 {minLength} 个数字',
							}
						]
					},
					password: {
						rules: [{
								required: true,
								errorMessage: '请输入密码',
							},
							{
								minLength: 6,
								maxLength: 15,
								errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					}
				}
			};
		},
		components: {
		},
		onLoad(options) {
			// 初始化页面,执行查看已授权信息
			// this.wxGetUserInfo();
			this.dologin()
		},
		methods: {
			
			// 1.wx获取登录用户code
			dologin(){
				let _this = this;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						// 小程序专有，用户登录凭证。开发者需要在开发者服务器后台，使用 code 换取 openid 和 session_key 等信息
						_this.code = loginRes.code;
						_this.wxGetUserInfo()
					},fail:function (fail){console.log("fail:",fail)}
				})
			},
			// 如果初始进入页面时点击了拒绝授权,如需要该权限,需要手动授权
			wxGetUserInfo(){ 
				let _this = this;
				// uni.showLoading({
				//   title: '登录中...'
				// });
				// 获取已授权类别
				uni.getSetting({
					success(res) {
						if (res.authSetting['scope.userInfo']) {
							//获取用户信息
							uni.getUserInfo({
								provider: 'weixin',
								success: function(infoRes) {
									// console.log('用户信息：',infoRes);
　　　　　　　　　　　				//获取用户信息后向调用信息更新方法
									_this.encryptedData = infoRes.encryptedData
									_this.iv = infoRes.iv
									_this.nickName = infoRes.userInfo.nickName; //昵称
									_this.avatarUrl = infoRes.userInfo.avatarUrl; //头像
									_this.updateUserInfo(); 
								},fail:function (fail){console.log("fail:",fail)}
							});
						}else if (!res.authSetting['scope.userInfo']) {
							// 尚未授权,
							// 则设置进入页面时主动弹出，直接授权
							uni.authorize({
								scope: 'scope.userInfo',
								success(res) {
									uni.getUserInfo({
										provider: 'weixin',
										success: function(infoRes) {
											// console.log('用户信息：',infoRes);
		　　　　　　　　　　　				//获取用户信息后向调用信息更新方法
											_this.encryptedData = infoRes.encryptedData
											_this.iv = infoRes.iv
											_this.nickName = infoRes.userInfo.nickName; //昵称
											_this.avatarUrl = infoRes.userInfo.avatarUrl; //头像
											_this.updateUserInfo(); 
										},
										fail:function (fail){console.log("fail:",fail)}
									});
								},fail() {
									console.log("授权失败")
								}
							})
						}
						
						if (res.authSetting['scope.userLocation']) {
							console.log("userLocation位置功能已授权")
							// 如果已授权,直接获取对应参数
							uni.getLocation({
								success(res) {
									// console.log(res)
									_this.longitude = res.longitude
									_this.latitude = res.latitude
								}
							})
						} else if (!res.authSetting['scope.userLocation']) {
							// 说明此时要获取的位置功能尚未授权,
							// 则设置进入页面时主动弹出，直接授权
							uni.authorize({
								scope: 'scope.userLocation',
								success(res) {
									console.log("授权成功,获取对应的位置参数")
									uni.getLocation({
										success(res) {
											_this.longitude = res.longitude
											_this.latitude = res.latitude
										}
									})
								},
								fail() {
									console.log("位置授权失败")
								}
							})
						}
					},
					fail() {
						console.log("获取授权信息授权失败")
					}
				})
				
			},
			//向后台获取OPENID
			updateUserInfo() { 
				let _this = this;
				var openId = uni.getStorageSync('openId');
				if(openId){ //如果已存在OPENID，则不需要向后台请求
					_this.openId = openId
					return false;
				}
				
				var data = {
					
					
					code:_this.code
				}
				getOpenid(data).then(res=>{
					_this.openId = res.data.openid
					_this.sessionKey = res.data.session_key
					uni.setStorageSync('openId', res.data.openid);
					// 暂时不需要解密,因为个人号无法获取手机号等敏感信息
					// _this.getDecodeUserInfo()
				}).catch(err=>{
					uni.showToast({
						icon:'none',
						title: err,
						duration: 2000
					})
				})
				
			},
			//解密信息
			getDecodeUserInfo() { 
				let _this = this;
				var data = {
					encryptedData:_this.encryptedData,
					iv:_this.iv,
					sessionKey:_this.sessionKey
				}
				decode(data).then(res=>{
					console.log("解密:",res)
					
				}).catch(err=>{
					uni.showToast({
						icon:'none',
						title: err,
						duration: 2000
					})
				})
			},
			bindGetUserInfo (e) {
				console.log(e.detail)
			},
			getPhoneNumber(val){
				console.log(val)
			},
			registForm(){
				let _this = this;
				this.$refs.form.submit().then(data => {
					data.wxcode = _this.openId
					data.remark = _this.latitude+","+_this.longitude
					regist(data).then(res=>{
						if(res.code == 20000){
							uni.showLoading({
								title:'注册成功...',
								mask: true,
							});
							setTimeout(()=>{
								this.submitForm()
							},1000)
						} else {
							uni.showToast({
								icon:'none',
								title: res.data.result,
								duration: 3000
							})
						}
						
					}).catch(err=>{
						uni.showToast({
							icon:'none',
							title: err,
							duration: 2000
						})
					})
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			submitForm() {
				let _this = this;
				this.$refs.form.submit().then(data => {
					data.wxcode = _this.openId
					data.remark = _this.latitude+","+_this.longitude
					login(data).then(res=>{
						// console.log(res)
						if(res.code == 20000){
							try {
							    uni.setStorageSync('tokey', res.data.token);
								uni.setStorageSync('username', data.username);
								
								setTimeout(()=>{
									uni.switchTab({
										url: '/pages/index/index'
									});
								},1000)
							} catch (e) {
							    console.log(e)
							}
						} else {
							uni.showToast({
								icon:'none',
								title: res.data.token,
								duration: 3000
							})
						}
						
					}).catch(err=>{
						uni.showToast({
							icon:'none',
							title: err,
							duration: 2000
						})
					})
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			}
		}
	}
</script>

<style>
	
</style>
